package com.iteaj.iot.test.simulator;

import com.iteaj.iot.config.ConnectProperties;
import com.iteaj.iot.simulator.dtu.SimulatorDtuConnectProperties;
import com.iteaj.iot.simulator.dtu.SimulatorDtuProtocol;
import com.iteaj.iot.test.IotTestHandle;
import com.iteaj.iot.test.IotTestProperties;
import com.iteaj.iot.test.server.dtu.DtuTestHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnExpression("${iot.test.dtu-start:false} and ${iot.test.server:false}")
public class DtuSimulatorTestHandle implements IotTestHandle {

    @Autowired
    private IotTestProperties testProperties;

    @Override
    public void start() throws Exception {
        System.out.println("------------------------------------------------ 开始DTU模拟测试 -----------------------------------------------------");
        ConnectProperties dtu = testProperties.getDtu();

        SimulatorDtuConnectProperties properties = new SimulatorDtuConnectProperties(testProperties.getServerHost(), dtu.getPort(), "test1")
            .setInterval(30).setHeartbeatMsg("test1").setHeartbeat(true).setProtocolHandle(protocol -> {
                byte[] message = protocol.responseMessage().getMessage();
                String msgStr = new String(message);

                /**
                 * dtu服务端是读请求给予响应原报文
                 */
                if(msgStr.contains("read")) {
                    new SimulatorDtuProtocol(message, protocol.getClientKey()).request();
                }

                /**
                 * 同步写返回OK
                 */
                if(msgStr.contains("sync")) {
                    new SimulatorDtuProtocol("OK".getBytes(), protocol.getClientKey()).request();
                }

                return null;
            });

        new SimulatorDtuProtocol("test".getBytes(StandardCharsets.UTF_8), properties).request();
        TimeUnit.SECONDS.sleep(1);
    }

    /**
     * 这个排序必须比 {@link DtuTestHandle#getOrder()} 小才能进行正常的测试
     * @return
     */
    @Override
    public int getOrder() {
        return 4950;
    }
}
